package com.ocean4.socialmap;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.lang.Character.UnicodeBlock;
import java.util.HashSet;
import java.util.Set;

import org.apache.http.protocol.ResponseConnControl;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.ocean4.socialmap.common.Utility;
import com.ocean4.volley.PhotoMultipartRequest;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.os.Build;
import android.provider.MediaStore;

public class EditPlaceActivity extends ActionBarActivity {

	private static final int PICK_IMAGE = 0;
	private final static String TAG_REQUEST = "MY_TAG";
	public static final String TAG = "EditPlaceActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_place);
		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.edit_place, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_save) {
			
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		ImageButton imgbAddImage;
		ImageView imgChoosenImage;
		private RequestQueue mVolleyQueue;
		private Set<String> fileList;

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_edit_place,
					container, false);
			imgChoosenImage = (ImageView) rootView.findViewById(R.id.imageView1);
			imgbAddImage = (ImageButton) rootView
					.findViewById(R.id.imgbAddImage);
			imgbAddImage.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Image_Picker_Dialog();
				}
			});
			
			fileList = new HashSet<String>();
			// Initialise Volley Request Queue. 
			mVolleyQueue = Volley.newRequestQueue(getActivity());

			//decodeFile("/storage/emulated/0/Screenshots/Screenshot_2014-09-04-15-50-20.jpg");
			return rootView;
		}
		
		/*
		 * Reference from : http://chintankhetiya.wordpress.com/2013/12/14/picture-selection-from-camera-gallery/
		 */
		public void Image_Picker_Dialog()
		{
			AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(getActivity());
			myAlertDialog.setTitle("Pictures Option");
			myAlertDialog.setMessage("Select Picture Mode");

			myAlertDialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface arg0, int arg1)
				{
					Utility.pictureActionIntent = new Intent(Intent.ACTION_GET_CONTENT, null);
					Utility.pictureActionIntent.setType("image/*");
					//Utility.pictureActionIntent.putExtra("return-data", true);
					startActivityForResult(Utility.pictureActionIntent, Utility.GALLERY_PICTURE);
				}
			});

			myAlertDialog.setNegativeButton("Camera", new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface arg0, int arg1)
				{
					// TODO : Change folder here
					File imagesFolder = Utility.Create_MY_IMAGES_DIR();
					String fileName = Utility.Get_Random_File_Name()+".jpg";
					File image = new File(imagesFolder, fileName);
					fileList.add(image.getAbsolutePath());
					Uri uriSavedImage = Uri.fromFile(image)	;
					
					Utility.pictureActionIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
					Utility.pictureActionIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
					if (Utility.pictureActionIntent.resolveActivity(getActivity().getPackageManager()) != null) {
						startActivityForResult(Utility.pictureActionIntent, Utility.CAMERA_PICTURE);
				    }
					
				}
			});
			myAlertDialog.show();

		}

		/**
		 * Opens dialog picker, so the user can select image from the gallery.
		 * The result is returned in the method <code>onActivityResult()</code>
		 */
		public void selectImageFromGallery() {
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(
					Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
		}

		/**
		 * Retrieves the result returned from selecting image, by invoking the
		 * method <code>Image_Picker_Dialog()</code>
		 */
		@Override
		public void onActivityResult(int requestCode, int resultCode,
				Intent data) {
			super.onActivityResult(requestCode, resultCode, data);
			if (resultCode == RESULT_OK){
				if (requestCode == Utility.GALLERY_PICTURE && data != null) {
					// data contains result
					// Do some task
					Uri selectedImage = data.getData();
					String[] filePathColumn = { MediaStore.Images.Media.DATA };

					Cursor cursor = getActivity().getContentResolver().query(selectedImage,
							filePathColumn, null, null, null);
					cursor.moveToFirst();

					int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
					String picturePath = cursor.getString(columnIndex);
					cursor.close();

					decodeFile(picturePath);
					Log.v(TAG, "Galerry photo: "+ picturePath);
				} else if (requestCode == Utility.CAMERA_PICTURE) {
					
					// This will get Thumbnail of the photo with low resolution.
			        
					decodeFile((String) fileList.toArray()[0]);
			        
					Log.v(TAG, "Capture photo: ");
				}
			} else if ( resultCode == RESULT_CANCELED) {

				Toast.makeText(getActivity(), " Picture was not taken ", Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(getActivity(), " Error on geting photo ", Toast.LENGTH_SHORT).show();
			}
		}
		
		public void Image_Selecting_Task(Intent data) {
		    try {
		        //Utility.uri = data.getData();
		        if (Utility.uri != null) {
		            // User had pick an image.
		            Cursor cursor = getActivity().getContentResolver().query(Utility.uri, new String[] {
		                android.provider.MediaStore.Images.ImageColumns.DATA
		            }, null, null, null);
		            cursor.moveToFirst();
		            // Link to the image
		            final String imageFilePath = cursor.getString(0);

		            //Assign string path to File
		            Utility.Default_DIR = new File(imageFilePath);

		            // Create new dir MY_IMAGES_DIR if not created and copy image into that dir and store that image path in valid_photo
		            Utility.Create_MY_IMAGES_DIR();

		            // Copy your image 
		            Utility.copyFile(Utility.Default_DIR, Utility.MY_IMG_DIR);

		            // Get new image path and decode it
		            Bitmap b = Utility.decodeFile(Utility.Paste_Target_Location);

		            // use new copied path and use anywhere 
		            String valid_photo = Utility.Paste_Target_Location.toString();
		            
		            //  TODO : Scale bitmap check.
		            b = Bitmap.createScaledBitmap(b, 150, 150, true);

		            //set your selected image in image view
		            imgChoosenImage.setImageBitmap(b);
		            
		            // Upload image
		            uploadPhotoRequest(Utility.Paste_Target_Location);
		            
		            cursor.close();

		        } else {
		            Toast toast = Toast.makeText(getActivity(), "Sorry!!! You haven't selecet any image.", Toast.LENGTH_LONG);
		            toast.show();
		        }
		    } catch (Exception e) {
		        // you get this when you will not select any single image
		    	Toast.makeText(getActivity(), "Sorry!!! You haven't selecet any image.", Toast.LENGTH_LONG).show();
		        Log.e("onActivityResult", "" + e);

		    }
		}

		/**
		 * The method decodes the image file to avoid out of memory issues. Sets
		 * the selected image in to the ImageView.
		 * 
		 * @param filePath
		 */
		public void decodeFile(String filePath) {

			// Decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(filePath, o);

			// The new size we want to scale to
			final int REQUIRED_SIZE = 2048;

			// Find the correct scale value. It should be the power of 2.
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
			while (true) {
				if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}

			// Decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2);
			
			Log.v(TAG, "Decoded file");

			imgChoosenImage.setImageBitmap(bitmap);
			
			// TODO : user resized file to upload.
			File file = new File(filePath);
			uploadPhotoRequest(file);
		}
		
		private void uploadPhotoRequest(File imageFile) {
			
			String url = "http://192.168.11.104/process/upload";
			
			Uri.Builder builder = Uri.parse(url).buildUpon();
//			builder.appendQueryParameter("api_key", "75ee6c644cad38dc8e53d3598c8e6b6c");
//			builder.appendQueryParameter("method", "flickr.interestingness.getList");
//			builder.appendQueryParameter("format", "json");
//			builder.appendQueryParameter("nojsoncallback", "1");
			
			PhotoMultipartRequest<JSONObject> photoUpload = new PhotoMultipartRequest<JSONObject>(url, 
					new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							Log.v(TAG, "Error Response "+ error.toString());
							// Handle your error types accordingly.For Timeout & No connection error, you can show 'retry' button.
							// For AuthFailure, you can re login with user credentials.
							// For ClientError, 400 & 401, Errors happening on client side when sending api request.
							// In this case you can check how client is forming the api and debug accordingly.
							// For ServerError 5xx, you can do retry or handle accordingly.
							if( error instanceof NetworkError) {
							} else if( error instanceof ServerError) {
							} else if( error instanceof AuthFailureError) {
							} else if( error instanceof ParseError) {
							} else if( error instanceof NoConnectionError) {
							} else if( error instanceof TimeoutError) {
							}
						}
					}, new Response.Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject response) {
							// TODO Auto-generated method stub
							if (response != null){
								Log.v(TAG, response.toString());
							} else {
								
							}
							
						}
					}, imageFile);
			
			
			
			//Set a retry policy in case of SocketTimeout & ConnectionTimeout Exceptions. Volley does retry for you if you have specified the policy.
			photoUpload.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
			photoUpload.setTag(TAG_REQUEST);	
			mVolleyQueue.add(photoUpload);
		}

	}

}
